package AS_source
{
			import Components.*;
			
			import com.yahoo.maps.api.YahooMap;
			import com.yahoo.maps.api.YahooMapEvent;
			import com.yahoo.maps.api.core.location.Address;
			import com.yahoo.maps.api.core.location.LatLon;
			import com.yahoo.maps.api.markers.SearchMarker;
			import com.yahoo.maps.api.markers.SimpleMarker;
			import com.yahoo.maps.api.overlays.PolylineOverlay;
			import com.yahoo.maps.webservices.geocoder.Geocoder;
			import com.yahoo.maps.webservices.geocoder.GeocoderResult;
			import com.yahoo.maps.webservices.geocoder.GeocoderResultSet;
			import com.yahoo.maps.webservices.geocoder.events.GeocoderEvent;
			import com.yahoo.maps.webservices.local.LocalSearch;
			import com.yahoo.maps.webservices.local.LocalSearchItem;
			import com.yahoo.maps.webservices.local.LocalSearchResults;
			import com.yahoo.maps.webservices.local.events.LocalSearchEvent;
			
			import flash.external.*;
			import Components.*;
	        import flash.events.Event;
			
			import mx.containers.Accordion;
			import mx.containers.HBox;
			import mx.containers.Panel;
			import mx.containers.TabNavigator;
			import mx.controls.Alert;
			import mx.controls.Text;
			import mx.core.UIComponent;
			import mx.events.ResizeEvent;
			import mx.containers.Grid;
			import mx.containers.GridRow;
			import mx.containers.GridItem;	
			import mx.controls.TextInput;
	public class MapView
	
	{
		var yahooID:String = "k6UXuM7V34HdFZRKgFrt3tgKtMXYo77mfalWFAqZv6hGmYsjVonm0BW1.2LCiwaag6OJaA--";
            
             var map:YahooMap; 
             var addressToFind:Address; 
             var sleectedLoc:LatLon;
             var geocoder:Geocoder;
             var centerMarker:SimpleMarker = null;;
             var searchMarkers:Array = null;
             var circleOverlay:PolylineOverlay = null;
             var drivingOverlay:PolylineOverlay = null;
             var tabNavi:TabNavigator;
			 var searchNavi:Accordion;
			 var mapTabOutput:UIComponent;
			 var mapBoxOutput:Panel;
			 var addressBoxOutput:TextInput;
			 var localBoxOutput:TextInput;
			 var distBoxOutput:TextInput;
			 var driveBoxOutput:TextInput;
			 
			 //schoolInfo.title = schoolName;
				//schoolInfo.locationLabel.text = address; from rank search.as
	
		public function MapView(tabControl:TabNavigator, searchControl:Accordion)
		{
			tabNavi=tabControl;
			searchNavi=searchControl;
			wrapper();
			addressButtonEvt();
		    appInit();
		    
		}
		function wrapper():void
		{
		var tester:HBox=HBox(tabNavi.getChildByName("mapContents"));
		var mapBox:Panel=Panel(tester.getChildByName("mapBox"));
		var UImap:UIComponent=UIComponent(mapBox.getChildByName("mapPanel"));
		mapTabOutput=UImap;
		mapBoxOutput=mapBox;
		
		}
		
		public function addressButtonEvt():void
		{
			
			var locSearch:Loc_Search_VBox=Loc_Search_VBox(searchNavi.getChildByName("locSearch"));
			
			var addressSearch:Grid=Grid(locSearch.getChildByName("addgrid"));
		
			var addressSearchrow:GridRow=GridRow(addressSearch.getChildByName("addgridrow"));
			
			var addressSearchitem:GridItem=GridItem(addressSearchrow.getChildByName("addgridItem"));
				
			
			
		var addressSearchtext:TextInput=TextInput(addressSearchitem.getChildByName("address"));
		
		    addressBoxOutput=addressSearchtext;
		    
		    var localSearch:Grid=Grid(locSearch.getChildByName("localsearchgrid"));
			var localSearchrow:GridRow=GridRow(localSearch.getChildByName("localsearchgridrow"));
			var localSearchitem:GridItem=GridItem(localSearchrow.getChildByName("localsearchgridItem"));
			var localSearchtext:TextInput=TextInput(localSearchitem.getChildByName("findSomthing"));
		    localBoxOutput=localSearchtext;
		    
		    var distSearch:Grid=Grid(locSearch.getChildByName("localsearchgrid"));
			var distSearchrow:GridRow=GridRow(distSearch.getChildByName("distsearchgridrow"));
			var distSearchitem:GridItem=GridItem(distSearchrow.getChildByName("distsearchgridItem"));
			var distSearchtext:TextInput=TextInput(distSearchitem.getChildByName("withinMiles"));
		    distBoxOutput=distSearchtext;
		    
		    var driveSearch:Grid=Grid(locSearch.getChildByName("localsearchgrid"));
			var driveSearchrow:GridRow=GridRow(driveSearch.getChildByName("drivesearchgridrow"));
			var driveSearchitem:GridItem=GridItem(driveSearchrow.getChildByName("drivesearchgridItem"));
			var driveSearchtext:TextInput=TextInput(driveSearchitem.getChildByName("driveTime"));
		    driveBoxOutput=driveSearchtext;
		    
		    
		    
		}
		
             function appInit():void  
            {                 
            	
                ExternalInterface.addCallback("createDriveTimePoly",createDriveTimePoly);
                
                // create a new YahooMap object.
                map = new YahooMap(); 
                // list for the MAP_INITIALIZE event from YahooMap
                map.addEventListener(YahooMapEvent.MAP_INITIALIZE, mapInit);
               
                // initialize the map, passing the app-id, width and height.
                map.init(yahooID, mapTabOutput.width, mapTabOutput.height);
    
                mapTabOutput.addChild(map); 
                mapTabOutput.addEventListener(ResizeEvent.RESIZE, handleContainerResize); 
                map.addPanControl(); 
                map.addZoomWidget(); 
                map.addTypeWidget();  
                
            } 
             
             function mapInit(event:YahooMapEvent):void  
            { 
            	
                map.addEventListener(YahooMapEvent.MAP_CLICK, handleMapClick);
                
                var center:LatLon = new LatLon(40.714, -74.006);
                map.zoomLevel = 7;
                map.centerLatLon = center;
                            
            } 
            
            
            function handleContainerResize(event:ResizeEvent):void {
                // set the size of the map based on its containers size.
                map.setSize(mapTabOutput.width, mapTabOutput.height); 
            }
            
             function addCenterMarker(loc:LatLon):void {
                centerMarker = new SimpleMarker();
                centerMarker.latlon = loc;
                map.markerManager.addMarker(centerMarker);
                map.centerLatLon = loc;
                
            }
                        
             function handleMapClick(event:YahooMapEvent):void {
                clearMapItems();
                addCenterMarker(event.data.latlon);
                
                geocoder = new Geocoder();
                geocoder.addEventListener(GeocoderEvent.GEOCODER_SUCCESS, handleReverseGeocoding);
                geocoder.reverseGeocode(centerMarker.latlon);

            }

             function handleReverseGeocoding(event:GeocoderEvent):void {
                var resultSet:GeocoderResultSet = event.data as GeocoderResultSet;
                var firstResult:GeocoderResult = resultSet.firstResult;
                
                mapBoxOutput.status = firstResult.getLineAddress();
                addressBoxOutput.text  = firstResult.getLineAddress();
            }
            
                public function handleFind(e:Event):void {
                this.clearMapItems();
                if (centerMarker != null){
                    searchAndShow(centerMarker.latlon);
                }
               
                else if (this.addressBoxOutput.text != "") {
                    addressToFind = new Address(addressBoxOutput.text); 
                    addressToFind.addEventListener(GeocoderEvent.GEOCODER_SUCCESS, handleGeocodeSuccess);
                    addressToFind.geocode(); 
                    //Alert.show("hello3");
                }
                else {
                    Alert.show('Need either type in address or click map to locate a point.', 'Missing Input', mx.controls.Alert.OK);
                }
            tabNavi.selectedIndex = tabNavi.getChildIndex(tabNavi.getChildByName("mapContents"));    
            }
            
            function handleGeocodeSuccess(event:GeocoderEvent):void  
            { 
               // var result:GeocoderResult = addressToFind.geocoderResultSet.firstResult; 
                
                var result:GeocoderResultSet = addressToFind.geocoderResultSet; 
                setLocation(result.firstResult);
               // map.zoomLevel = result.zoomLevel; 
                clearMapItems();
                addCenterMarker(map.centerLatLon);                
                searchAndShow(map.centerLatLon);
                
            } 

           function setLocation(result:GeocoderResult):void
            {
                // set the zoom level, center latlon and set the text field with the full address.
                map.zoomLevel = result.zoomLevel;
                map.centerLatLon = result.latlon;
                
            }
            function searchAndShow(loc:LatLon):void {
                            
                var localSearch:LocalSearch = new LocalSearch();
                localSearch.addEventListener(LocalSearchEvent.SEARCH_SUCCESS, handleSearchSuccess);
                localSearch.searchLocal(localBoxOutput.text, 
                                        map.zoomLevel, 
                                        loc, 
                                        Number(this.distBoxOutput.text), 1, 25 );
                
                drawCircle(map.centerLatLon, Number(this.distBoxOutput.text));
                
                var m:String = ExternalInterface.call("getDriveTimePoly", 
                                                      map.centerLatLon.lat.toString(), 
                                                      map.centerLatLon.lon.toString(), 
                                                      this.driveBoxOutput.text);
                
            }
        
             function handleSearchSuccess(event:LocalSearchEvent):void {
                var searchResults:LocalSearchResults = event.data as LocalSearchResults;
                var results:Array = searchResults.results;
                var len:int = results.length;
                
                searchMarkers = new Array();
                
                for(var i:int=0; i<len; i++) {
                    var item:LocalSearchItem = results[i];
                    var marker:SearchMarker = new SearchMarker(item);
                    
                    map.markerManager.addMarker(marker);
                    searchMarkers[i] = marker;    
                }
            }                         

            function createDriveTimePoly(geomtry:Array, index:int):String {
                var colors:Array = [0x009999, 0x00FF99, 0x9999FF]
                var poly:Array = new Array();        
                
                drivingOverlay = new PolylineOverlay();
                
                drivingOverlay.mouseEnabled=false;
                drivingOverlay.fillColor = colors[index % 3];
                drivingOverlay.fillAlpha = 0.30;
                drivingOverlay.lineColor = 0xFFFF80;
                drivingOverlay.lineThickness = 2;
                drivingOverlay.lineAlpha = 0.60;
                map.overlayManager.addOverlay(drivingOverlay);
                                                            
                for( var i:int =0; i=geomtry.length; i++){
                    var a:Array = geomtry.pop() as Array;
                    var lon:Number = Number(a[0]);
                    var lat:Number = Number(a[1]);
                    var point:LatLon = new LatLon(lat, lon);
                    poly.push(point);
                }
                // pass latlon values into the polyline data provider to draw the overlay. 
                drivingOverlay.dataProvider = poly;
                map.zoomLevel = map.zoomLevel - 1;
                 
                return "done";
            } 
            
             function drawCircle(point:LatLon, miles:Number):void {
                var latRadius:Number = miles/69;
                var lonRadius:Number = miles/(Math.cos(point.lon*Math.PI/180)*111.315);
                
                var circlePoints:Array = new Array();
                
                for (var i:int=0; i<=360; i++){
                    var cPoint:LatLon = new LatLon(point.lat + latRadius*Math.sin(i*Math.PI/180), 
                                                   point.lon + lonRadius*Math.cos(i*Math.PI/180));
                    circlePoints[i] = cPoint;                    
                    lonRadius = miles /(Math.cos(cPoint.lon*Math.PI/180)*111.315);
                }
                                
                circleOverlay = new PolylineOverlay();
                
                circleOverlay.mouseEnabled=false;                
                circleOverlay.fillAlpha = 0.10;
                circleOverlay.fillColor = 0xFF0000;
                circleOverlay.lineColor = 0xFF0000;
                circleOverlay.lineThickness = 1;
                circleOverlay.lineAlpha = 0.5;
                circleOverlay.dataProvider = circlePoints;
                map.overlayManager.addOverlay(circleOverlay);
                map.zoomLevel = map.zoomLevel + 1;
                
            }
            
             function clearMapItems():void {
                if( centerMarker != null ) {
                    map.markerManager.removeMarker(centerMarker);
                    centerMarker = null;
                }
                
                if (circleOverlay != null){
                    map.overlayManager.removeOverlay(circleOverlay);
                    circleOverlay = null;
                }
                
                if (searchMarkers != null){
                    for( var i:int =0; i< searchMarkers.length; i++) {
                        map.markerManager.removeMarker(searchMarkers[i]);
                    }
                    searchMarkers = null;
                }
                
                if (drivingOverlay != null ) {
                    map.overlayManager.removeOverlay(drivingOverlay);
                    drivingOverlay = null;
                }
		}

	}
}